package com.gzy.studentsociety.web;

import com.gzy.studentsociety.dao.SocietyDao;
import com.gzy.studentsociety.dao.SocietyDaoImpl;
import com.gzy.studentsociety.dao.StudentDao;
import com.gzy.studentsociety.dao.StudentDaoImpl;
import com.gzy.studentsociety.entity.Society;
import com.gzy.studentsociety.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

/**
 * @version: java version 1.8
 * @Author: Chuan Liu
 * @description:
 * @date: 2024-10-31 10:38
 */
@WebServlet(name = "AddSocietyServlet", value = "/society/addSociety")
public class AddSocietyServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        String intro = req.getParameter("intro");
        Society society = new Society();
        society.setSocietyIntro(intro);
        society.setSocietyName(name);
        society.setSocietyStatus(1);
        //获取session中登录者为创建者
        String number = (String)(req.getSession().getAttribute("student"));
        StudentDao studentDao = new StudentDaoImpl();
        SocietyDao societyDao = new SocietyDaoImpl();
        // 获取学生id
        try {
            society.setSocietyCreator(studentDao.findByNumber(number).getStudentId());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            req.setAttribute("exception",throwables);
            req.getRequestDispatcher("/WEB-INF/jsp/error.jsp");
        }

        // 协会添加创建时间
        society.setSocietyCreateDate(new Date());
        int result = -1;
        try {
            result = societyDao.insertSociety(society);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            req.setAttribute("exception",throwables);
            req.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(req,res);
        }

        res.sendRedirect(req.getContextPath()+"/society/mainIndex");
    }

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

    }
}
